import { Directive } from '@angular/core';
import { NgControl } from '@angular/forms';
import { Observable } from 'rxjs/internal/Observable';
import { MemberService } from '../services/member.service';

@Directive({
  selector: '[validate-onblur]',
  host: {
    '(focus)': 'onFocus($event)',
    '(blur)': 'onBlur($event)'
  }
})
export class NamesUnionValidatorDirective {

  constructor(public formControl: NgControl, private memberService: MemberService) { }
  //://stackoverflow.com/questions/43553544/how-can-i-manually-set-an-angular-form-field-as-invalid
  //://stackoverflow.com/questions/33866824/angular2-formcontrol-validation-on-blur
  onFocus($event: Event) {
    this.formControl.control?.markAsUntouched({ onlySelf: false });
  }

  onBlur($event: Event) {
    this.formControl.control?.markAsTouched({ onlySelf: true });
    let v: string = this.formControl.value;
    this.getResult(v).subscribe({
      next: response => {
        this.formControl.control?.setErrors(null);
      },
      error: err => {
        this.formControl.control?.setErrors({ namesUnion: true });
      },
      complete: () => { console.log('[NamesUnionValidator-Directive]Completed'); }
    });
  }

  getResult(val: string): Observable<string> {
    return this.memberService.isExistsNames(val);
  }
}
